import { Component, OnDestroy, OnInit } from '@angular/core';
import { FormBuilder, FormGroup } from '@angular/forms';
import { ActivatedRoute, Router } from '@angular/router';
import { Constant, ServiceResult } from '@core/constant';
import { EmitterService } from '../../../../service/emit.service';
import { CommService } from '../../../../service/comm/comm.service';
import { TranslateService } from '@ngx-translate/core';
import { NzMessageService, UploadFile } from 'ng-zorro-antd';
import { PopService } from '../../../../service/pop/pop.service';
import { ProductService } from '../../../../service/prod/product.service';
import { catchError } from 'rxjs/operators';
import { of } from 'rxjs/index';

@Component({
  selector: 'pop-pops-add-pop-item',
  templateUrl: './add-pop-item.component.html',
  styleUrls: ['./add-pop-item.component.less'],
})
export class PopPopsAddPopItemComponent implements OnInit, OnDestroy {
  constructor(
    private fb: FormBuilder,
    private trans: TranslateService,
    private cnt: Constant,
    private router: Router,
    private popService: PopService,
    private msg: NzMessageService,
    private productService: ProductService,
    private comm: CommService,
    private activatedRouter: ActivatedRoute,
    private emit: EmitterService,
  ) {}

  ngOnInit(): void {
    this.loadBrands();
    this.imgSuffix = this.comm.getGoodsUrl();
    this.uploadUrl = this.productService.uploadUrl();
    setTimeout(() => {
      this.emit.sendMessage('HIDE_REUSE_TAB');
    }, 100);
    this.activatedRouter.params.subscribe(params => {
      this.popItem.id = params['id'];
      if (this.popItem.id === undefined) {
        return;
      }
      if (
        this.popItem.id != null ||
        this.popItem.id !== '' ||
        undefined !== this.popItem.id
      ) {
        console.log(this.popItem.id);
        this.title = this.trans.instant('edit-single-pop');
        this.isEdit = true;
        this.loadPopItem(this.popItem.id);
      }
      // 获取POP详情
    });
  }

  ngOnDestroy() {
    this.emit.sendMessage('SHOW_REUSE_TAB');
  }

  back() {
    this.router.navigate(['/pop/list/pops/list']);
  }
  title = this.trans.instant('add-single-pop');
  priceUnits = [{ text: '$', value: 'USD' }, { text: '€', value: 'EUR' }];
  isEdit = false;
  brands = [];
  loadBrands() {
    const lang = this.trans.currentLang || this.trans.defaultLang;
    this.brands = [];
    this.comm.getBrand().subscribe(data => {
      const ret: ServiceResult = <ServiceResult>data;
      if (ret.status === 200) {
        for (const row of ret['data']['rows']) {
          this.brands.push({
            text: lang === 'en' ? row.labelEnUs : row.labelDefault,
            value: row.value,
          });
        }
      }
    });
  }
  popItem: any = {
    id: null,
    sap: null,
    sku: null,
    description: null,
    sapDesc: null,
    img: null,
    material: null,
    brand: null,
    exw: null,
    cif: null,
    qty: null,
    ctnQty: null,
    priceUnit: null,
    status: null,
    grossWeight: null,
    netWeight: null,
  };

  previewImage = '';
  previewVisible = false;
  imgSuffix = '';
  loading = false;
  // 预览图片地址
  picUrl = '';
  // 图片上传地址
  uploadUrl = '';

  beforeUpload = (file: File) => {
    const isJPG = file.type === 'image/jpeg';
    const isPNG = file.type === 'image/png';
    if (!isJPG && !isPNG) {
      this.msg.warning(`不支持的格式: ${file.type}`);
    }
    const isLt2M = file.size / 1024 / 1024 < 2;
    if (!isLt2M) {
      this.msg.warning('图片不能超过2MB!');
    }
    return (isJPG || isPNG) && isLt2M;
  };

  private getBase64(img: File, callback: (img: any) => void) {
    if (img) {
      const reader = new FileReader();
      reader.addEventListener('load', () => callback(reader.result));
      reader.readAsDataURL(img);
    }
  }

  handleChange(info: { file: UploadFile }): void {
    if (info.file.status === 'uploading') {
      this.loading = true;
      return;
    }
    if (info.file.status === 'done') {
      this.getBase64(info.file.originFileObj, (img: any) => {
        this.popItem.img = info.file.response.rows[0].id;
        this.picUrl = this.comm.getGoodsUrl() + this.popItem.img;
      });
    }
    if (info.file.status === 'error') {
      this.msg.error(info.file.error.error);
    }
  }
  salestatus = true;

  reset() {
    this.popItem.sku = null;
    this.popItem.sap = null;
    this.popItem.description = null;
    this.popItem.img = null;
    this.popItem.material = null;
    this.popItem.brand = null;
    this.popItem.exw = null;
    this.popItem.cif = null;
    this.popItem.qty = null;
    this.popItem.ctnQty = null;
    this.popItem.priceUnit = null;
    this.popItem.status = null;
    this.popItem.netWeight = null;
    this.popItem.grossWeight = null;
    this.salestatus = true;
  }

  isEmpty(str): boolean {
    if (str === undefined || str === '' || str === null || str === NaN) {
      return true;
    }
    return false;
  }

  checkForm(): boolean {
    if (this.isEmpty(this.popItem.sku)) {
      this.msg.create('info', 'SKU描述');
      return false;
    }
    if (this.isEmpty(this.popItem.sap)) {
      this.msg.create('info', 'SAP物料号');
      return false;
    }
    if (this.isEmpty(this.popItem.exw)) {
      this.msg.create('info', 'EXW价格');
      return false;
    }
    if (this.isEmpty(this.popItem.qty)) {
      this.msg.create('info', 'QTY');
      return false;
    }
    if (this.isEmpty(this.popItem.ctnQty)) {
      this.msg.create('info', '装箱数');
      return false;
    }
    if (this.isEmpty(this.popItem.brand)) {
      this.msg.create('info', '请选择品牌');
      return false;
    }
    return true;
  }

  save() {
    if (!this.checkForm()) {
      return;
    }
    this.popItem.priceUnit = 'USD';
    this.popItem.status = this.salestatus ? 'normal' : 'disabled';
    this.popService
      .savePopItem(this.popItem)
      .pipe(
        catchError(err => {
          return of(err);
        }),
      )
      .subscribe(ret => {
        if (ret.status === 200 || ret.code === 200) {
          this.msg.create('success', '保存成功');
          setTimeout(this.back(), 300);
        } else {
          if (ret.msg) {
            this.msg.create('error', ret.msg);
          } else {
            this.msg.create('error', ret.message);
          }
        }
      });
  }

  private loadPopItem(id) {
    this.popService
      .listPopItemById(id)
      .pipe(
        catchError(err => {
          return of(err);
        }),
      )
      .subscribe(ret => {
        if (ret.status === 200 || ret.code === 200) {
          this.popItem = ret.data;
          this.salestatus = this.popItem.status === 'normal' ? true : false;
        } else {
          if (ret.msg) {
            this.msg.create('error', ret.msg);
          } else {
            this.msg.create('error', ret.message);
          }
        }
      });
  }
}
